package com.imooc.order.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.imooc.order.client.ProductClient;
import com.imooc.order.dataobject.OrderDetail;
import com.imooc.order.dataobject.OrderMaster;
import com.imooc.order.dataobject.ProductInfo;
import com.imooc.order.dto.CartDTO;
import com.imooc.order.dto.OrderDTO;
import com.imooc.order.enums.OrderStatusEnum;
import com.imooc.order.enums.PayStatusEnum;
import com.imooc.order.repository.OrderDetailRepository;
import com.imooc.order.repository.OrderMasterRepository;
import com.imooc.order.service.OrderService;
import com.imooc.order.utils.KeyUtil;

/**
 * @author jack
 * @date 2019年1月4日
 */
@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private ProductClient productClient;
	@Autowired
	private OrderDetailRepository orderDetailRepository;
	@Autowired
	private OrderMasterRepository orderMasterRepository;

	/**
	 * 1、查询商品（调商品服务） 
	 * 2、计算总价
	 * 3、扣库存（调商品服务）
	 * 4、订单入库
	 */
	@Override
	public OrderDTO create(OrderDTO orderDTO) {
		String orderId = KeyUtil.genUniqueKey();

		// 1、查询商品（调商品服务）
		List<String> productIdList = orderDTO.getOrderDetailList().stream().map(OrderDetail::getProductId)
				.collect(Collectors.toList());
		List<ProductInfo> productInfoList = productClient.listForOrder(productIdList);

		// 2、计算总价
		BigDecimal amount = BigDecimal.ZERO;
		for (OrderDetail orderDetail : orderDTO.getOrderDetailList()) {
			for (ProductInfo productInfo : productInfoList) {
				if (productInfo.getProductId().equals(orderDetail.getProductId())) {
					BeanUtils.copyProperties(productInfo, orderDetail);
					orderDetail.setDetailId(KeyUtil.genUniqueKey());
					orderDetail.setOrderId(orderId);
					orderDetailRepository.save(orderDetail);

					amount = orderDetail.getProductPrice().multiply(new BigDecimal(orderDetail.getProductQuantity()))
							.add(amount);
				}
			}
		}
		
		//3、扣库存（调商品服务）
		List<CartDTO> cartDTOList = orderDTO.getOrderDetailList()
				.stream().map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
				.collect(Collectors.toList());
		productClient.decreaseStock(cartDTOList);
		
		//4、订单入库
		OrderMaster orderMaster = new OrderMaster();
		BeanUtils.copyProperties(orderDTO, orderMaster);
		orderMaster.setOrderId(orderId);
		orderMaster.setOrderAmount(amount);
		orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
		orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
		orderMasterRepository.save(orderMaster);
		
		orderDTO.setOrderId(orderId);
		return orderDTO;
	}

}
